package servlet;


import dao.TuitionRecordDao;
import vo.TuitionRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/one_page_tuition_records")
public class one_page_tuition_records extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();

        String key = request.getParameter("id");

        if (key == null) {

            int currentIndex, count, size = 10;
            String index = request.getParameter("index");
            if (index == null)
                index = "1";
            currentIndex = Integer.parseInt(index);

            try {
                TuitionRecordDao tuitionRecordDao = new TuitionRecordDao();
                count = tuitionRecordDao.getCount();
                ArrayList<TuitionRecord> tr = tuitionRecordDao.getOnePage(currentIndex, size);
                int sumIndex = count % size == 0 ? count / size : count / size + 1;
                session.setAttribute("onePageTuitionRecords", tr);
                session.setAttribute("sumIndex", sumIndex);
                response.sendRedirect("teacher/tuition_record.jsp");
            } catch (Exception e) {
                out.print(e);
            }
        }
        else {
            TuitionRecordDao tuitionRecordDao = new TuitionRecordDao();
            try {
                TuitionRecord tuitionRecord = tuitionRecordDao.findWithId(key);
                ArrayList<TuitionRecord> tuitionRecords = new ArrayList<>();
                tuitionRecords.add(tuitionRecord);
                session.setAttribute("onePageTuitionRecords", tuitionRecords);
                session.setAttribute("sumIndex", 1);
                response.sendRedirect("teacher/tuition_record.jsp");
            } catch (Exception e) {
                out.print(e);
            }
        }
    }
}
